﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PdfLibrary
{
    public class PdfIndirectObject : IPdfObject
    {
        public int objectNumber;
        public int generationNumber;
        public IPdfObject content;

        public bool LoadFromReader(PdfReader reader, bool throwException)
        {
            var originalPosition = reader.Position;

            var errorMsg = LoadFromReaderInner(reader);
            var hasError = errorMsg != null;
            var exc = throwException && hasError ? new PdfParsingException(reader, errorMsg) : null;

            if(hasError)
                reader.Position = originalPosition;

            if (throwException && hasError)
                throw exc;

            return !hasError;
        }

        private string LoadFromReaderInner(PdfReader reader)
        {
            if (!int.TryParse(reader.ReadWord(), out this.objectNumber))
                return "PdfIndirectObject parsing error: objectNumber is not an int!";

            if (!int.TryParse(reader.ReadWord(), out this.generationNumber))
                return "PdfIndirectObject parsing error: generationNumber is not an int!";

            if (reader.ReadWord() != "obj")
                return "PdfIndirectObject parsing error: 'obj' not found!";

            this.content = PdfObject.CreateFromReader(reader);

            if (reader.ReadWord() != "endobj")
                return "PdfIndirectObject parsing error: 'endobj' not found!";

            return null;
        }
    }
}
